<?php

namespace App\Task\GuildManage;

use App\Amqp\Producer\GuildSettlementProducer;
use App\Constants\GuildCode;
use App\Model\Guild\GuildManage;
use Hyperf\Amqp\Producer;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 每天定时结算公会
 * @Crontab(name="GuildSettlementTask", rule="0 5,10,12 * * *", callback="execute", memo="异步结算公会余额", singleton=false)
 */
class GuildSettlementTask
{
    //0 6,10,15 * * *
    /**
     *
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function execute()
    {
        //查找所有公会
        $guilds = GuildManage::getGuilds();
        if (empty($guilds)) {
            return;
        }

        if (date('Y-m-d H:i:s') >= GuildCode::BEGIN_DATA) {
            $this->runData($guilds);
        }
    }

    /**
     * 跑数据
     * @param $guildInfos
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    private function runData($guildInfos)
    {
        if (empty($guildInfos)) {
            return;
        }

        foreach ($guildInfos as $one) {
            $message = new GuildSettlementProducer(['guild_id' => $one['id']]);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $producer->produce($message);
        }
    }

}